package db4oClass.appClass;

import general.appClass.SystemInfo;
import general.dbClass.DBCategory;
import general.dbClass.DBKeyword;
import general.dbClass.DBPicInfo;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.db4o.ObjectContainer;

import db4oClass.daoClass.*;

/**
 * Servlet implementation class db4oImgUpdateApp
 */
@WebServlet("/db4oImgUpdateApp")
public class db4oImgUpdateApp extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public db4oImgUpdateApp() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html; charset=UTF-8");

		//System Information Manage Class
		ObjectContainer 	container = SystemInfo.getDb4oConn(request);
		
		//Parameter "action"
		String action = request.getParameter("action");
		if (action != null && action.equals("deleteImage")) {
			this.deleteImage(request, response, container);
			return;
		}
		if (action != null && action.equals("updateImage")) {
			this.updatePhotoInfo(request, response, container);
			return;
		}
		if (action != null && action.equals("updateImageTooltip")) {
			this.updateImageTooltip(request, response, container);
			return;
		}

	}

	/**
	 * update Photo's information
	 * @param request					request from browser
	 * @param response					response to browser
	 * @param container					connection with db4o database
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePhotoInfo(HttpServletRequest request,HttpServletResponse response, ObjectContainer container)
			throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("bnr"));
		String name = request.getParameter("imgName");
		int rate = Integer.parseInt(request.getParameter("imgRate"));
		ArrayList<DBCategory> categories = new ArrayList<DBCategory>();
		ArrayList<DBKeyword> keywords = new ArrayList<DBKeyword>();

		String[] selectedCategories = request.getParameterValues("category");
		String selectedKeywords = request.getParameter("keywords");
		
		if (selectedCategories!=null){
			for (int i = 0; i < selectedCategories.length; i++) {
				DBCategory tmp = Db4oDaoGet.getCategoryById(container, Integer.parseInt(selectedCategories[i]));
				categories.add(tmp);
			}	
		}
		

		String delims = ",";
		String[] keywordsInput = selectedKeywords.split(delims);

		for (int i = 0; i < keywordsInput.length; i++) {
			if (keywordsInput[i].equals(""))
				break;
			
			DBKeyword tmp = Db4oDaoGet.getTagById(container,Integer.parseInt(keywordsInput[i]));
			keywords.add(tmp);
		}

		DBPicInfo picInfo = new DBPicInfo(nr, name, rate, categories,keywords);
		
		
		String url = "";
		if(Db4oDaoUpdate.updatePhotoById(container, picInfo)) {
			request.setAttribute("msg", "Update Picture successfully!");
			url = response.encodeURL("/successful.jsp");
		}else {
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", "photo's id doesn't exist!");
			url = response.encodeURL("/errorInfo.jsp");
		}
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param con
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updateImageTooltip(HttpServletRequest request,HttpServletResponse response, ObjectContainer container)
			throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("bnr"));
		String name = request.getParameter("imgName");
		int rate = 0;
		try{
			rate = Integer.parseInt(request.getParameter("imgRate"));	
		}catch(Exception e){
			rate = 0;
		}
		
		ArrayList<DBCategory> categories = new ArrayList<DBCategory>();
		ArrayList<DBKeyword> keywords = new ArrayList<DBKeyword>();

		String[] selectedCategories = request.getParameterValues("category");
		String[] selectedKeywords = request.getParameterValues("keyword");
		
		if (selectedCategories!=null){
			for (int i = 0; i < selectedCategories.length; i++) {
				DBCategory tmp = Db4oDaoGet.getCategoryById(container, Integer.parseInt(selectedCategories[i]));
				categories.add(tmp);
			}	
		}
		
		if (selectedKeywords!=null){
			for (int i = 0; i < selectedKeywords.length; i++) {
				DBKeyword tmp = Db4oDaoGet.getTagById(container,Integer.parseInt(selectedKeywords[i]));
				keywords.add(tmp);
			}	
		}
		
		DBPicInfo picInfo = new DBPicInfo(nr, name, rate, categories,keywords);

		
		String url = "";
		if(Db4oDaoUpdate.updatePhotoById(container, picInfo)) {
			url = response.encodeURL("/"+SystemInfo.getMode(request.getSession())+"ImgInfoApp?action=tooltip&bnr="+nr);
		}else {
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", "photo's id doesn't exist!");
			url = response.encodeURL("/errorInfo.jsp");
		}
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	
	/**
	 * delete Photo Application
	 * @param request				request from browser
	 * @param response				response to browser
	 * @param container				connection with db4o database
	 * @throws ServletException
	 * @throws IOException
	 */
	private void deleteImage(HttpServletRequest request,HttpServletResponse response, ObjectContainer container)
			throws ServletException, IOException {
		
		String[] bnrStringArray = request.getParameterValues("bnr");
		
		for (int i = 0; i < bnrStringArray.length; i++) {
			int id = Integer.parseInt(bnrStringArray[i]);
			Db4oDaoUpdate.deletePhotoById(container, id);
		}
				
		request.setAttribute("msg", "delete Image successfully!");	
		String url = response.encodeURL("/successful.jsp");	
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
}
